<template>
  <ElConfigProvider :locale="zhCn">
    <div class="dialog-table">
      <div>
        <slot name="search" :query="props.query" :sort="sort" :row="props.row"></slot>
      </div>
      <!-- 表格 -->
      <div class="dialog-table-table" v-loading="loading">
        <slot name="table" :data="data" :page="page" :sort="sort" />
      </div>
      <!-- 分页器 -->
      <div class="dialog-table-pagination">
        <slot name="pagination" :page="page" :total="total" />
      </div>
    </div>
  </ElConfigProvider>
</template>

<script setup lang="ts">
import { withDefaults, ref, reactive, onMounted, defineExpose } from 'vue'
import { ElConfigProvider  } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn'

interface Props {
  row?: object;
  query: object;
  api: (params?: any, row?: any) => Promise<any>;
}
const props = withDefaults(defineProps<Props>(), {
  query: () => ({}),
  api: () => Promise.resolve({ page: 1, size: 10, total: 0, data: [] })
})

const loading = ref(false)
const data = ref<Array<any>>([])
const page = reactive({
  page: 1,
  size: 10
})
const sort = reactive({
  sidx: '',
  order: ''
})
const total = ref(0)
const selection = ref([])

// 获取数据
const getData = () => {
  const params = {
    page: {
      index: page.page,
      size: page.size
    },
    sort,
    condition: {
      ...props.query
    }
  }
  loading.value = true
  return props.api(params, props.row).then(res => {
    data.value = res.list || []
    total.value = res.totalCount || 0
  }).finally(() => {
    loading.value = false
  })
}

// 换页
const changePage = (change: { page?: number, size: number }) => {
  Object.assign(page, change)
  getData()
}

// 排序
const sortChange = ({ prop, order }) => {
  const map = {
    ascending: 'asc',
    descending: 'desc'
  }
  sort.order = map[order] || ''
  sort.sidx = prop
  getData()
}

// 刷新
const refresh = () => {
  page.page = 1
  getData()
}

// 选择
const selectionChange = (sel) => {
  selection.value = sel || []
}

// 挂在获取数据
onMounted(() => {
  getData()
})

defineExpose({
  getData,
  changePage,
  refresh,
  sortChange,
  selectionChange
})
</script>

<style scoped lang="scss">
.dialog-table {
  box-sizing: border-box;
  padding: 25px 20px;
}
</style>
